package com.udp;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;

/**UDP 通信的实现  传递自定义对象类型
 * 创建服务端*/
public class ObjectTypeServer {
    public static void main(String[] args) {
        DatagramSocket datagramSocket = null;
       // ByteArrayInputStream bis = null;//字节数组输入流
        ObjectInputStream ois = null;//对象输入流
        try{
            //创建DatagramSocket对象，监听接收数据端口9999
           datagramSocket = new DatagramSocket(9999);
           //创字节数组
            byte[] b = new byte[1024];
            //创建DatagramPacket 封装数据
            DatagramPacket dp = new DatagramPacket(b,b.length);
            datagramSocket.receive(dp);//发送数据
            //发送的是字节数组，现在要的是对象 所以要转型
            ois = new ObjectInputStream(new ByteArrayInputStream(dp.getData()));
            System.out.println(ois.readObject());

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(datagramSocket != null){
                datagramSocket.close();
            }
            if(ois != null){
                try {
                    ois.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
